import { ElMessage } from 'element-plus';
/**
 * 下载文件
 * @returns
 */
export function downloadFile(res: any, filename: string = '') {
	if (!res) {
		return false;
	}
	if (res.type === 'application/json') {
		toMessage(res);
		return false;
	}
	console.log(res.headers);
	let url = window.URL.createObjectURL(new Blob([res]));
	let link = document.createElement('a');
	link.style.display = 'none';
	link.href = url;
	link.setAttribute('download', filename == '' ? decodeURI(res.headers['content-disposition'].split('=')[1]) : filename);
	document.body.appendChild(link);
	link.click();
}

const toMessage = (res) => {
	const reader = new FileReader();
	reader.readAsText(res, 'utf-8'); // 读取blob数据为文本
	reader.onload = function (e) {
		try {
			// 将读取到的文本解析为JSON对象
			const jsonData = JSON.parse(e.target.result);
			ElMessage.error(jsonData.message);
		} catch (error) {
			console.error('Error parsing JSON:', error);
		}
	};
};
